package com.zhangxujie.litewords.ui.recite;

import android.annotation.SuppressLint;
import android.content.Context;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.CompoundButton;
import android.widget.LinearLayout;
import android.widget.Switch;

import androidx.annotation.NonNull;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentManager;
import androidx.fragment.app.FragmentStatePagerAdapter;
import androidx.lifecycle.ViewModelProviders;
import androidx.swiperefreshlayout.widget.SwipeRefreshLayout;
import androidx.viewpager.widget.PagerAdapter;
import androidx.viewpager.widget.ViewPager;

import com.zhangxujie.litewords.R;
import com.zhangxujie.litewords.api.Const;
import com.zhangxujie.litewords.ui.cardview.PagerData;
import com.zhangxujie.litewords.ui.cardview.PagerFragment;
import com.zhangxujie.litewords.dao.WordsDAO;
import com.zhangxujie.litewords.db.AppDatabase;
import com.zhangxujie.litewords.db.DBUtil;
import com.zhangxujie.litewords.entity.Words;

import java.util.ArrayList;
import java.util.List;

public class ReciteFragment extends Fragment {

    //    private
    private Handler handler = null;

    private ReciteViewModel reciteViewModel;

    private List<PagerData> mPagerData = new ArrayList<>();

    private ViewPager mViewPager;

    private List<Words> wordsList = null;

    private SharedPreferences mSpf;

    private Switch switch1;
    private Switch switch2;
    private Switch switch3;

    SwipeRefreshLayout swipeRefreshLayout;


    //存储数据
    private static ReciteFragment instancefragment;
    private static Bundle savedState;


    @SuppressLint("HandlerLeak")
    public View onCreateView(@NonNull final LayoutInflater inflater,
                             final ViewGroup container, final Bundle savedInstanceState) {

//        wordsList = (ArrayList<Words>) saveState().get("wordlist");
        reciteViewModel =
                ViewModelProviders.of(this).get(ReciteViewModel.class);
        final View root = inflater.inflate(R.layout.fragment_recite, container, false);
        LinearLayout recite_settingbar = root.findViewById(R.id.recite_settingbar);
        mViewPager = root.findViewById(R.id.view_pager);

        mSpf = getActivity().getSharedPreferences("setting", Context.MODE_PRIVATE);

        initSwitch(root);


        FragmentManager fragmentManager = getFragmentManager();

        final PagerAdapter adapter = new FragmentStatePagerAdapter(fragmentManager) {

            //实现动态刷新view必须覆盖的方法
            @Override
            public int getItemPosition(@NonNull Object object) {
                return POSITION_NONE;
            }

            @NonNull
            @Override
            public Fragment getItem(int position) {
                System.out.println(position);
                Fragment result = null;
                if (mPagerData != null) {
                    result = PagerFragment.newInstance(mPagerData.get(position));
                }
                return result;
            }

            @Override
            public int getCount() {
                System.out.println(mPagerData);
                if (mPagerData == null) {
                    return 0;
                }
                return mPagerData.size();
            }

        };
        mViewPager.setAdapter(adapter);

        handler = new Handler() {
            @Override
            public void handleMessage(Message msg) {
                List<Words> wordsList = (List<Words>) msg.obj;
                mPagerData.clear();//需要先清除原来的数据，再添加十个
                for (Words w : wordsList) {
                    mPagerData.add(new PagerData(w.imgUrl, w.word, w.explaination, w.id));
                }
                //更新了数据，必须用adapter.notifyDataSetChanged来通知线程
                adapter.notifyDataSetChanged();
                mViewPager.setCurrentItem(0);//重置index=0位置
            }
        };

        //刷新单词列表
        flushWordsList();


        //设置setting-bar是否显示
        recite_settingbar.setVisibility(mSpf.getBoolean(Const.SETTING_RECITE_SETTINGBAR, true) ? View.VISIBLE : View.INVISIBLE);

        //初始化监听器
        initListeners(adapter);


        return root;
    }

    private void initListeners(final PagerAdapter adapter) {
        switch1.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                if (buttonView.isPressed()) {
                    SharedPreferences.Editor editor = mSpf.edit();
                    editor.putInt(Const.RECITE_SETTING_REMEMBER, isChecked ? 1 : 0);
                    editor.commit();
                    adapter.notifyDataSetChanged();
                }

            }
        });

        switch2.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                if (buttonView.isPressed()) {
                    SharedPreferences.Editor editor = mSpf.edit();
                    editor.putInt(Const.RECITE_SETTING_2, isChecked ? 1 : 0);
                    editor.commit();
                    adapter.notifyDataSetChanged();
                }


            }
        });

        switch3.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                if (buttonView.isPressed()) {
                    SharedPreferences.Editor editor = mSpf.edit();
                    editor.putInt(Const.RECITE_SETTING_LOADIMG, isChecked ? 1 : 0);
                    editor.commit();
                    adapter.notifyDataSetChanged();
                }
            }
        });


        //下拉刷新
        swipeRefreshLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
            @Override
            public void onRefresh() {
//                Toast.makeText(getActivity(), "刷新", Toast.LENGTH_SHORT).show();//刷新时要做的事情
                flushWordsList();
                adapter.notifyDataSetChanged();
//                getActivity().recreate();
                swipeRefreshLayout.setRefreshing(false);//刷新完成
            }
        });


        swipeRefreshLayout.setRefreshing(false);//为false时 停止刷新效果
    }


    private void initSwitch(View root) {

        switch1 = root.findViewById(R.id.switch_recite_1);
        switch2 = root.findViewById(R.id.switch_recite_2);
        switch3 = root.findViewById(R.id.switch_recite_3);
        swipeRefreshLayout = root.findViewById(R.id.refresh);//初始化下拉刷新控件，


        switch1.setChecked(mSpf.getInt(Const.RECITE_SETTING_REMEMBER, 0) == 1);
        switch2.setChecked(mSpf.getInt(Const.RECITE_SETTING_2, 0) == 1);
        switch3.setChecked(mSpf.getInt(Const.RECITE_SETTING_LOADIMG, 0) == 1);

    }


    private void flushWordsList() {
        //刷新单词列表
        final AppDatabase db = DBUtil.getDb(getContext());
        new Thread() {
            @Override
            public void run() {
                int wordsNum = Math.max(mSpf.getInt(Const.NUM_OF_WORDS, Const.DEFAULT_WORDS_NUM), 5);
                WordsDAO dao = db.wordsDao();
                wordsList = dao.loadRandomNWords(wordsNum);
                Message msg = new Message();
                msg.obj = wordsList;
                handler.sendMessage(msg);

            }
        }.start();
    }


}
